package com.xzp.controller;

import com.xzp.entity.Girl;
import com.xzp.entity.Result;
import com.xzp.exception.GirlException;
import com.xzp.repository.GirlRepository;
import com.xzp.service.GirlService;
import com.xzp.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
public class GirlController {


    @Autowired
    private GirlRepository girlRepository;


    @Autowired
    private GirlService girlService;

    @GetMapping("/girls")
    public List<Girl> girlList(){
        return girlService.girlList();
    }



    @PostMapping("/girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){  //使用对象接受参数 验证结果保存在对象

        //未验证通过
        if (bindingResult.hasErrors())
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());  //调用工具类

        return girlService.girlAdd(girl);
    }
    @GetMapping(value = "/girls/{id}")
    public Result<Girl> girlFindOne(@PathVariable("id") Integer id){
//        return girlRepository.findOne(id); 老版本写法
        return girlService.girlFindOne(id);
    }

    //更新信息
    @PutMapping(value = "/girls/{id}")
    public Result<Girl> girlUpdate(@PathVariable("id") Integer id, @Valid Girl girl,BindingResult bindingResult){

        if (bindingResult.hasErrors())
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());  //调用工具类

        girl.setId(id);

        return girlService.girlUpdate(girl);

    }

    @DeleteMapping(value = "/girls/{id}")
    public Result girlDelete(@PathVariable("id") Integer id){

       return girlService.girlDelete(id);
    }

    @GetMapping(value = "/girls/age")
    public List<Girl> findByAge(@RequestParam("age") Integer age){
        return girlRepository.findByAge(age);
    }

    /**
     * 插入两个女生
     */
    @PostMapping(value = "/girls/two")
    public void girlTwo(){
        girlService.insertTwo();
    }
    @GetMapping(value = "/girls/getAge/{id}")
    public Result getAge(@PathVariable("id") Integer id) throws Exception{
       return girlService.getAge(id);
    }

}
